﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using WebApplication3.Data;
using WebApplication3.Data.Entities;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
	//[Route("customer")]
    public class CustomerController : BaseController
	{
		private readonly ApplicationDbContext applicationDbContext;
		private readonly UserManager<AppIdentityUser> userManager;

		public CustomerController(
			ApplicationDbContext applicationDbContext,
			UserManager<AppIdentityUser> userManager):base(applicationDbContext)
		{
			this.applicationDbContext = applicationDbContext;
			this.userManager = userManager;
		}

		//[Route("bind")]
		public IActionResult Bind( [FromBody] CustomerBindModel model)
        {
			if (!ModelState.IsValid)
				return ValidationProblem();

			var user = this.applicationDbContext.Users.SingleOrDefault(s => s.OpenId == model.OpenId);

			user.CNName = model.UserName;
			user.Mobile = model.Mobile;
			user.ShopNo = model.ShopNo;

			this.applicationDbContext.SaveChanges();
			//userManager.UpdateAsync(user);


			return Ok();
        }

		//[ActionName("info")]
		[HttpGet]
		public IActionResult Info(string openid)
		{
			//if (!User.Identity.IsAuthenticated)
			//	return Ok("请登录");

			 
			var user = GetUser(openid);
			var products = this.applicationDbContext.Products.Where(s=>s.OpenId==openid).ToList();

			return Ok(new {  products,  UserName =user.CNName, Mobile=user.Mobile, ShopNo=user.ShopNo });
			  
			  
		}
		[HttpPost]
		public IActionResult SetProducts(   string openid,string list ) {
			return Ok();
			var jsonObj =list.DeserializeObject<List<string>>();
			var user = GetUser(openid);

			var products = this.applicationDbContext.Products.Where(s=>s.OpenId==openid).ToList()  ;
			this.applicationDbContext.Products.RemoveRange(products);


			var addProducts = new List<Product>();
			jsonObj.ForEach(s=> { addProducts.Add(new Product {  UserId=user.Id,OpenId=openid,ProductName=s}); });

			this.applicationDbContext.AddRange(addProducts);

			this.applicationDbContext.SaveChanges();
			return Ok();
		}
	}
}